#include "substitute_all.h"
#include "find_all.h"




std::string substitute_all( std::string input, std::string toBeFound, std::string newSubString ) {

  std::string result;
  result.clear();

  // empty input
  if ( input.length()==0 )
    return input;

  // nothing to be substituted
  if ( toBeFound.length()==0 )
    return input;

  // using replace algorithm can make the job only for single characters
  //   so the following is a quick-and-dirty workaround on this (actually, not so quick and very dirty)
  //   a more elegant way is possible, you can contribute!
  std::vector<size_t> positions = find_all( input, toBeFound );

  // no matches
  if ( positions.size()==0 )
    return input;

  // if this point is reached, at least 1 match is found
  size_t index = 0;

  size_t start; //, end;
  start=0;
//  end=positions[0];

  while ( index < positions.size() ) {

    result.append(input.substr( start, positions[index]-start ) );
    result.append( newSubString );
    start =  positions[index]+toBeFound.size();
    index++;

    // if this is the last match, the remaining part of the string should be copied as it is
    if ( index == positions.size() )
      result.append( input.substr( start, input.size()-start) );
  }


  return result;
}
